
from rsa import *
import random

public_key, private_key = make_key_pair(12) # safe for n<100

alice_money = 3 #random.randint(1,9)
bob_money   = 7 #random.randint(1,9)

def main(_alice_money, _bob_money):
    print("Alice has %d(i) millions." % _alice_money)
    print("Bob has %d(j) millions." % _bob_money)
    print("Alice generate a pair of RSA key:")
    print("public-key: {} , which is shared in public". format(public_key))
    print("private-key: {} , which is only hold by Alice\n". format(private_key))
    
    # 1、Bob挑选了一个非常大的整数x
    x = random.randint(1000, 2000)

    # 2、Bob用Alice的公钥加密x，得到k
    print("Step 1: Bob generate a large random number: ". format(x))
    k = public_key.encrypt(x)
    print("\tBob encrypt it with the shared public-key to generate a cipher k: {}". format(k))
    
    # 3、Bob把自己的资产数 j（_bob_money） 隐含到一个计算中去，即把k-j，然后Bob就把计算结果发给Alice
    print("\tthen Bob send c=k-j({}-{}={}) to Alice\n". format(k, _bob_money, k-_bob_money))
    c = k - _bob_money # c=k-j

    p = 29
    d = []
    for i in range(c+1, c+11): # 即1～10个数，不包含c+11
        # 4、Alice开始解密，然后做取模运算，将自己的资产数隐含到这组数据中去
        # 参考文中的3、4、5小节
        d.append(private_key.decrypt(i) % p)
    
    print("Step 2: Alice decrypt c+1, ... c+10 with his own private key:")
    print("\t{}". format(d))

    # 5、Alice从上面的结果中找到第i个数，从第i个数开始+1，即把自己的资产数隐含到了其中，然后把计算结果发送给Bob
    for i in range(_alice_money, 10):
        d[i] = d[i] + 1
    print("\n\tAlice add 1 to c+i+1 to c+10: ")
    print("\t{}". format(d))

    # Bob开始验证结果，对于Bob来说，他只关注第j个结果，即dj，也即他一开始选择的大整数x，计算一下 x mod p的结果
    print("Step 3: Bob test whether x mod p equals to d[j]. \n\t if so, i>=j\n\totherwise, i<j\n")
    print("d[j] is {}, x mod p is {}". format(d[_bob_money-1], x % p))
    # 如果 (x mod p) == dj（说明dj这个数没有被Alice加1），则可得出 j <= i，即Bob >= Alice，否则，Bob < Alice
    # 从左往右数，越往右数字越大
    if (x % p == d[_bob_money-1]): # Bob <= Alice 
        return True
    else:
        return False # Bob > Alice

if __name__ == '__main__':
    result = main(alice_money, bob_money)
    print(result)
    print(bob_money <= alice_money)
    if result: 
        print("Bob <= Alice")
    else:
        print("Bob > Alice")
